package cn.studyjava.verify.code12306.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.studyjava.verify.code12306.common.Const;
import cn.studyjava.verify.code12306.common.action.BaseAction;
import cn.studyjava.verify.code12306.common.enums.VerifyEnum;
import cn.studyjava.verify.code12306.common.result.JsonResult;
import cn.studyjava.verify.code12306.model.ImgVerify;
import cn.studyjava.verify.code12306.model.vo.AuthVO;
import cn.studyjava.verify.code12306.service.IVerifyService;
import cn.studyjava.verify.code12306.util.IpUtil;

/**
 * <p>
 * Description:
 * </p>
 * 
 * @author: zsljava
 * @version 1.0.0
 * <p>
 * History:
 * -----------------------------------------------
 * @Date: 2017年10月16日 下午5:43:03
 * @author: zsljava
 * @version 1.0.0
 * @OP: Create
 * -----------------------------------------------
 * </p>
 *
 * @since
 * @see
 */
@Controller
public class VaildateController extends BaseAction {

//	private static final Logger log = LoggerFactory.getLogger(VaildateController.class);

	@Autowired
	private IVerifyService verifyService;
	
	@GetMapping("")
	public String index() {
		return "index";
	}

	/**
	 * 
	 * @Title: verify
	 * @Description: 返回验证码
	 * @param request
	 * @param response
	 * @return
	 * @return: JsonResult<ImgVerify>
	 */
	@ResponseBody
	@GetMapping("verifiy")
	public JsonResult<ImgVerify> verify(HttpServletRequest request, HttpServletResponse response) {
		ImgVerify verifyCode = verifyService.getVerifyCode();
		return buildJsonResult(verifyCode);
	}

	/**
	 * 
	 * @Title: verifyCode
	 * @Description: 校验结果
	 * @param code
	 * @param offset
	 * @param appId
	 * @param request
	 * @return
	 * @return: JsonResult<AuthVO>
	 */
	@ResponseBody
	@PostMapping("verifiy")
	public JsonResult<AuthVO> verifyCode(@RequestParam("code") String code, @RequestParam("offset") String offset, @RequestParam("appId") String appId, HttpServletRequest request){
		String newKey = Const.REDIS_ALREADY_PREFIX.concat(code);
		String ip = IpUtil.getIpAddr(request);
		AuthVO auth =  verifyService.verify(appId, newKey, offset, ip);
		if(auth.getStatus() == Const.VERIFY_STATUS_SUCCESS){
			return buildJsonResult(auth);
		}else{
			return buildFialJsonResult(VerifyEnum.getEnumByCode(auth.getReasonCode()), auth);
		}
	}
}